package com.itheima.dao;

import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface RoleDao {

    @Select("select * from role where id in (select roleId from users_role where userId=#{userId}) ")
    @Results({
            @Result(id=true,property = "id",column ="id"),
            @Result(property = "roleName",column ="roleName"),
            @Result(property = "roleDesc",column ="roleDesc"),
            @Result(property = "permissions",column ="id",javaType=java.util.List.class, many = @Many(select="com.itheima.dao.PermissionDao.findPermissionByRoleId"))
    })
    public List<Role> findRoleByUserId(Integer userId)throws Exception;

    @Select("select * from role")
    List<Role> findAll()throws Exception;

    @Insert("insert into role(roleName,roleDesc) value(#{roleName},#{roleDesc})")
    void addRole(Role role);

    @Select("select * from role where id=#{roleId}")
    @Results({
            @Result(id=true,column = "id",property = "id"),
            @Result(column = "roleName",property = "roleName"),
            @Result(column = "roleDesc",property = "roleDesc"),
            @Result(column = "id",property = "permissions",javaType = java.util.List.class,
                    many = @Many(select = "com.itheima.dao.PermissionDao.findPermissionByRoleId"))
    })
    Role findById(int roleId);

    @Select("select * from permission where id not in (select permissionId from role_permission where id=#{roleId})")
    List<Permission> findOtherPermission(int roleId);

    @Insert("insert into role_permission(roleId,permissionId) values(#{roleId},#{permissionId})")
    void addPermissionToRole(@Param("roleId") int roleId,@Param("permissionId") int permissionIds);
}
